from django.contrib import admin
from .models import Address
from apps.accounts.models import User
from django.utils.html import format_html

class AddressAdmin(admin.ModelAdmin):
    list_display = (
        'user_info', 
        'full_address', 
        'contact', 
        'phone', 
        'is_default',
        'is_locked'
    )
    list_filter = ('province', 'city', 'is_default', 'is_locked')
    search_fields = ('contact', 'phone', 'province', 'city', 'district')
    readonly_fields = ('created_at', 'updated_at', 'is_locked')
    actions = ['set_as_default', 'unlock_address']

    fieldsets = (
        ('用户信息', {'fields': ('user',)}),
        ('联系人信息', {'fields': ('contact', 'phone')}),
        ('地址详情', {'fields': (
            'province', 
            'city', 
            'district', 
            'address_detail',
            'latitude',
            'longitude'
        )}),
        ('状态', {'fields': ('is_default', 'is_locked')}),
        ('时间', {'fields': ('created_at', 'updated_at')}),
    )

    def user_info(self, obj):
        return f"{obj.user.username}({obj.user.id})"
    user_info.short_description = '用户'

    def full_address(self, obj):
        return f"{obj.province}{obj.city}{obj.district}{obj.address_detail[:20]}"
    full_address.short_description = '完整地址'

    def set_as_default(self, request, queryset):
        for address in queryset:
            address.is_default = True
            address.save()
        self.message_user(request, f"已设置 {queryset.count()} 个地址为默认地址")
    set_as_default.short_description = "设为默认地址"

    def unlock_address(self, request, queryset):
        queryset.update(is_locked=False)
        self.message_user(request, f"已解锁 {queryset.count()} 个地址")
    unlock_address.short_description = "解锁地址"

admin.site.register(Address, AddressAdmin)